# -*- coding = utf-8 -*-
import csv
import random
import math
import operator


# 将数据导入，并划分进训练集与测试集
def loadDataset(filename, split, trainingSet=[], testSet=[]):
    with open(filename, 'rt', encoding="utf-8") as csvfile:
        lines = csv.reader(csvfile)
        dataset = list(lines)
        for x in range(len(dataset) - 1):
            for y in range(4):
                dataset[x][y] = float(dataset[x][y])
            if random.random() < split:
                trainingSet.append(dataset[x])
            else:
                testSet.append(dataset[x])


# 计算欧几里得距离
def euclideanDistance(instance1, instance2, length):
    distance = 0
    for x in range(length):
        distance += pow((instance1[x] - instance2[x]), 2)
    return math.sqrt(distance)


# 计算最近的k个近邻
def getNeighbors(trainingSet, testInstance, k):
    distances = []
    length = len(testInstance) - 1
    for x in range(len(trainingSet)):
        dist = euclideanDistance(testInstance, trainingSet[x], length)
        distances.append((trainingSet[x], dist))
    distances.sort(key=operator.itemgetter(1))  # sort函数默认为升序
    neighbors = []
    for x in range(k):
        neighbors.append(distances[x][0])  # 得到k个近邻
    return neighbors


# 计算测试样例属于哪个类别
def getResponse(neighbors):
    classVotes = {}  # 定义一个字典，方便计算类别个数
    for x in range(len(neighbors)):
        response = neighbors[x][-1]
        if response in classVotes:
            classVotes[response] += 1
        else:
            classVotes[response] = 1
    sortedVotes = sorted(classVotes.items(), key=operator.itemgetter(1), reverse=True)  # 降序排列
    return sortedVotes[0][0]


# 计算准确率
def getAccuracy(testSet, predictions):
    correct = 0
    for x in range(len(testSet)):
        if testSet[x][-1] == predictions[x]:

            correct += 1
    return correct/len(testSet) * 100.0


def main():
    trainingSet = []
    testSet = []
    split = 0.67  # 设置训练集:测试集为2:1
    loadDataset('/workspace/PythonProject/iris.data', split, trainingSet, testSet)  # 导入数据
    print("Train set:", len(trainingSet))
    print("Test set:", len(testSet))

    predictions = []
    k = 3  # 计算最近的3个近邻
    for x in range(len(testSet)):
        neighbors = getNeighbors(trainingSet, testSet[x], k)
        result = getResponse(neighbors)
        predictions.append(result)
        print('>predicted = ', result, ', actual = ', testSet[x][-1])
    accuracy = getAccuracy(testSet, predictions)
    print("Accuracy: ", accuracy, '%')


if __name__ == "__main__":
   main()
